package com.vspush.tcp.core;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;


public class Client {
	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		Bootstrap b = new Bootstrap();
		b.group(group).channel(NioSocketChannel.class);
		b.handler(new ChannelInitializer<SocketChannel>(){
			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
					@Override
					public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception {
						ByteBuf in = ((ByteBuf) msg);
						StringBuffer sb = new StringBuffer();
					        while (in.isReadable()) {
					        	@SuppressWarnings("resource")
								ByteBufInputStream bbis = new ByteBufInputStream(in);
					        	String str = bbis.readLine();
					        	sb.append(str+"\r\n");
					        	if(str.length()==0){
					        		break;
					        	}
					        }
					    System.out.println(sb.toString());
					    ctx.close();
					}
					@Override
				    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
				        cause.printStackTrace();
				        ctx.close();
				    }
					
					
				});
				
			}});
		try {
			ChannelFuture future = b.connect(new InetSocketAddress("127.0.0.1", 9636));
			Channel channel = future.sync().channel();
	        channel.writeAndFlush(Unpooled.copiedBuffer("server  this is a test", CharsetUtil.UTF_8));
	        channel.closeFuture().sync();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			group.shutdownGracefully();
		}
		
		
	}

}
